﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.IdentityModel.Tokens;
using NLog.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using Vue.Admin.Common;
using Vue.Admin.Models;

namespace Vue.Admin.Api
{
    public class Startup
    {
        //注入配置服务
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            //配置jwt信息 映射到内存中
            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
            var jwtSettings = new JwtSettings();
            Configuration.Bind("JwtSettings", jwtSettings);//全局绑定jwt配置文件信息
            //配置mvc信息
            services.AddMvc()
                    .AddJsonOptions(options => options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver())//取消驼峰命名法
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                    .AddJsonOptions(options =>
                {
                    options.SerializerSettings.DateFormatString = "yyyy/MM/dd HH:mm:ss";//全局设置时间字段返回格式为yyyy/MM/dd HH:mm:ss
                });
            //匹 配swagger信息
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Vue.Admin.API",
                    Description = "A Vue Project's API "
                });

                //添加token头
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "请输入带有Bearer的Token",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
                var security = new Dictionary<string, IEnumerable<string>>
                {
                    {"Bearer", new string[] { }},
                };
                //Json Token认证方式，此方式为全局添加 版本为2.2版本
                options.AddSecurityRequirement(security);
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //加载api文档注释和依赖的model注释和tools注释
                var xmlPath = Path.Combine(basePath, "Vue.Admin.Api.xml");
                var xmlPath1 = Path.Combine(basePath, "Vue.Admin.Models.xml");
                var xmlPath2 = Path.Combine(basePath, "Vue.Admin.Tools.xml");
                //第二个参数是用于开启控制器注释的 不给或者为false就不会显示控制器注释，只会显示接口方法注释
                options.IncludeXmlComments(xmlPath, true);
                options.IncludeXmlComments(xmlPath1, true);
                options.IncludeXmlComments(xmlPath2, true);
            });
            //添加权限验证
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                //主要是jwt  token参数设置
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    //Token颁发机构
                    ValidIssuer = jwtSettings.Issuer,
                    //颁发给谁
                    ValidAudience = jwtSettings.Audience,
                    //这里的key要进行加密，需要引用Microsoft.IdentityModel.Tokens
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
                    ValidateIssuerSigningKey = true,
                    ////是否验证Token有效期，使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateLifetime = true,
                    ////允许的服务器时间偏移量
                    ClockSkew = TimeSpan.Zero

                };
            });
            //添加数据库上下文
            services.AddDbContext<DBContext>();
        }


        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler();
            }
            //注入日志管道
            loggerFactory.AddNLog();
            //注入jwt验证管道
            app.UseAuthentication();
            //使用默认路由
            app.UseMvcWithDefaultRoute();
            //使用swagger
            app.UseSwagger();
            //使用swaggerUI
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Vue.Admin.API");
            });
        }
    }
}
